<?php

namespace App\Services\Admin\V1;

use App\Models\V1\Menu;
use App\Models\V1\Role;
use App\Models\V1\Admin;
use Illuminate\Support\Str;
use App\Models\V1\Permission;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests\Admin\V1\AdminStoreRequest;
use App\Http\Requests\Admin\V1\AdminUpdateRequest;

class AdminService
{
    /**
     * @expalin GET USER INFO OF ALL
     * @param int $page_size
     * @return LengthAwarePaginator
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/29/16:08
     */
    public function paginate(int $page_size): LengthAwarePaginator
    {
        return Admin::with(['roles'])->recent()->where('is_enable', '=', Admin::ENABLE_TRUE)->paginate($page_size);
    }

    /**
     * @expalin GET USER INFO BY ID
     * @param int $id
     * @return Admin
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/29/14:56
     */
    public function find(int $id): Admin
    {
        return Admin::where('is_enable', '=', Admin::ENABLE_TRUE)->findOrFail($id);
    }

    /**
     * @expalin ADD USER INFO
     * @param AdminStoreRequest $request
     * @return Admin
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/30/10:56
     */
    public function store(AdminStoreRequest $request): Admin
    {
        $admin = null;

        DB::transaction(function () use (&$admin, $request) {
            $role = Role::enable()->find($request->input('role_id'));
            $admin = new Admin();
            $admin->uuid = Str::uuid();
            $admin->name = $request->input('name');
            $admin->username = $request->input('username');
            $admin->nickname = $request->input('nickname');
            $admin->email = $request->input('email') ?? '';
            $admin->password = Hash::make($request->input('password'));
            $admin->is_enable = $request->input('is_enable') ? Admin::ENABLE_TRUE : Admin::ENABLE_FALSE;
            $admin->save();

            $admin->assignRole($role);
        });

        return $admin;
    }

    /**
     * @expalin UPDATE USER INFO
     * @param Admin $admin
     * @param AdminUpdateRequest $request
     * @return Admin
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/30/14:34
     */
    public function update(Admin $admin, AdminUpdateRequest $request): Admin
    {
        DB::transaction(function () use (&$admin, $request) {
            $password = $request->input('password');
            $role = Role::enable()->find($request->input('role_id'));
            $admin->uuid = Str::uuid();
            $admin->name = $request->input('name');
            $admin->username = $request->input('username');
            $admin->nickname = $request->input('nickname');
            $admin->email = $request->input('email') ?? '';

            if ($password) {
                $admin->password = bcrypt($password);
            }

            $admin->is_enable = $request->input('is_enable') ? Admin::ENABLE_TRUE : Admin::ENABLE_FALSE;
            $admin->save();

            $admin->assignRole($role);
        });

        return $admin;
    }

    /**
     * @expalin DELETE USER
     * @param Admin $admin
     * @return bool
     * @throws \Exception
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/30/11:21
     */
    public function destroy(Admin $admin): bool
    {
        return (bool) $admin->delete();
    }

    /**
     * @expalin 返回用户所有权限（剔除管理员）
     * @param Admin $admin
     * @return Collection|\Illuminate\Support\Collection
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/16:55
     */
    public function getPermissions(Admin $admin): Collection
    {
        if ($admin->isSuper()) {
            $permissions = Permission::getPermissions();
        } else {
            $permissions = $admin->getAllPermissions();
        }

        return $permissions;
    }

    /**
     * @expalin 返回用户所有菜单（剔除管理员）
     * @param Admin $admin
     * @return Collection
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/16:56
     */
    public function getRoleMenus(Admin $admin): Collection
    {
        if ($admin->isSuper()) {
            $menus = Menu::enable()->get();
        } else {
            $menus = new Collection();

            foreach ($admin->roles as $role) {
                $menus = $menus->merge($role->menus()->enable()->get());
            }

            $menus = $menus->unique('id');
        }

        return $menus;
    }
}
